package service

import (
	"context"
	"fmt"
	"log"
	"net/http"
)

func Start(ctx context.Context, serviceName, host, port string, registerHanlersFunc func()) (context.Context, error) {
	registerHanlersFunc()
	ctx = startService(ctx, serviceName, host, port)
	return ctx, nil
}

func startService(ctx context.Context, serviceName, host, port string) context.Context {
	ctx, cancel := context.WithCancel(ctx)

	var srv http.Server
	srv.Addr = ":" + port

	go func() {
		// 如果启动http服务器失败，就会调用下面cancel(),就会发送信号
		log.Println(srv.ListenAndServe()) // srv.ListenAndServe()返回error类型
		cancel()
	}()

	go func() {
		fmt.Printf("%v started. Press any key to stop. \n", serviceName)
		var s string
		fmt.Scanln(&s)
		srv.Shutdown(ctx) //关闭服务
		// 这里手动停止也会发送信号
		cancel()
	}()

	return ctx
}
